<?php

namespace App\Repository\Repositories;

use App\Repository\Models\ArticleCategory;
use App\Repository\Repositories\Interfaces\SysArticleRepository;
use App\Repository\Models\SysArticle;

/**
 * Class SysArticleRepositoryEloquent.
 *
 * @package namespace App\Repository\Repositories;
 */
class SysArticleRepositoryEloquent extends BaseRepository implements SysArticleRepository
{
    /**
     * 搜索
     * @var array
     */
    protected $fieldSearchable = ['fid'=>'in'];

    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return SysArticle::class;
    }


    public function indexNewList($fid){

        $data = $this->query()->where(['fid'=>$fid,'audit'=>1,'recommend'=>1])->select('id','pid','title')->orderBy('id','desc')->limit(4)->get()->toArray();

        return $data;
    }


    public function upDownNewList($id){

        $up = $this->query()->where([['id','<',$id],'audit'=>1])->select('id','pid','title')->orderBy('id','desc')->first();//上一篇
        $up = $up ? $up->toArray() : null;

        $down = $this->query()->where([['id','>',$id],'audit'=>1])->select('id','pid','title')->first();//下一篇
        $down = $down ? $down->toArray() : null;

        return $data=['up'=>$up,'down'=>$down];
    }

    /**
     * TODO 获取 指定 分类下的所有分类id
     * @return array
     * */
    public function getSysCateList($id){

        try{
            $cateList = $this->getChildren($id);
            $cateList[]['id'] = $id; // 返回本身 id
        }catch (\Exception $e){
            return false;
        }
        return $cateList;
    }

    /**
     *
     * TODO 递归遍历获取该节点下的所有子分类
     *
     * */
    private function getChildren($id){
        $list = ArticleCategory::query()->where('fid',$id)->orderBy('sort','asc')->get(['id'])->toArray();
        foreach ($list as $key=>&$value){
            $children = self::getChildren($value['id']);
            if (count($children)>0){
                $value['children'] = $children;
            }
        }
        return array_filter($list);
    }


}
